from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

# 打开浏览器
def open_browser(browser:str='Chrome'):
    if browser.capitalize() == 'Chrome':
        return webdriver.Chrome()
    elif browser.capitalize()=='Chrome_with_opt':
        user_data=r'--user-data-dir=c:\Users\33126\App\Data\Local\Google\Chrome\User Data'
        options=webdriver.ChromeOptions()
        options.add_argument(user_data)
        return webdriver.Chrome(options=options)
    elif browser.capitalize() == 'Chrome_with_headless':
        options = webdriver.ChromeOptions()
        options.add_argument("--headless")
        return webdriver.Chrome(options=options)
    elif browser.capitalize() == 'Firefox':
        return webdriver.Firefox()
    elif browser.capitalize() == 'Edge':
        return webdriver.Edge()
    else:
        print('请输入正确的浏览器名称，目前仅支持Chrome、Firefox、Edge浏览器')
class Base:
    def __init__(self,driver):
        self.driver = driver

    def get_url(self,url):
        try:
            self.driver.get(url)
            self.driver.implicitly_wait(15)
            self.driver.maximize_window()
        except:
            print('浏览器打开失败，无法输入网址')

    # 定位一个元素
    def find_elenent(self,locator:tuple,timeout:int=10):
        try:
            return WebDriverWait(self.driver,timeout).until(EC.presence_of_element_located(locator))
        except:
            print(f'元素{locator}未找到')
            return False

    # 输入文本
    def send_keys(self,locator,text):
        try:
            element = self.find_elenent(locator)
            element.clear()
            element.send_keys(text)
        except:
            print(f'元素{locator}未找到，无法输入')

    # 点击元素
    def click(self,locator):
        try:
            element = self.find_elenent(locator)
            element.click()
        except:
            print(f'元素{locator}未找到，无法点击')
    #获取元素文本值
    def get_element_text(self,loctor):
        try:
            element=self.find_elenent(loctor)
            return element.text
        except:
            print(f'元素{loctor}未找到，无法获取文本值')
    #获取元素某个属性值
    def get_element_value(self,locator,attribute):
        try:
            element = self.find_elenent(locator)
            return element.text
        except:
            print(f'元素{locator}未找到，无法获取文本值')

# 自测代码
if __name__ == '__main__':
    base = Base(open_browser())
    base.get_url('http://172.16.0.137/shop/')
    search_locator = (By.NAME,'word')
    button_locator = (By.CLASS_NAME,'btn')
    base.send_keys(search_locator,'真皮女包')
    base.click(button_locator)
    sleep(5)
    base.driver.quit()



